<template>
	<view class="market-cart">
		<view class="hede">
			<view class="t1">
				<text>购物车</text>
				<text>({{ total }})</text>
			</view>
			<uv-search shape="square" v-model="keyword" bgColor="#fff" v-if="!isEdit" :showAction='false'
				borderColor="#F5F5F5" placeholder="搜索购物车商品" placeholderColor="#B1B1B1" />
			<view class="t2" @click="isEdit = !isEdit">{{ isEdit ? '退出管理' : '管理' }}</view>
		</view>

		<catrList :list="list" v-model:checkbox="checkList" />
		<uv-gap height="80" bgColor="transparent" />
		<view class="jiesuan">
			<view class="flex align-center">
				<uv-checkbox-group v-model="check1">
					<uv-checkbox shape="circle" name="all" activeColor="#BC2721" label="全选" @change="checkAll" />
				</uv-checkbox-group>
			</view>
			<view class="flex align-center">
				<text class="hj_lbl" v-if="!isEdit">合计:</text>
				<text class="hj_price" v-if="!isEdit">¥{{totalPrice}}</text>
				<button type="button" class="btn" v-if="isEdit" @click="delArrTips">删除({{checkList.length}})</button>
				<button type="button" class="btn" v-else @click="handleSettlement">结算</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		watch
	} from 'vue';
	import {
		storeToRefs
	} from "pinia"
	import {
		useUserStore, useMarketStore
	} from '@/store'
	import {
		getMarketCartList,
		delMarketCart
	} from '@/api'

	import catrList from './cart_list.vue'


	const user = useUserStore()
	const market = useMarketStore()
	const {
		token
	} = storeToRefs(user)

	const page = ref(1)
	const list = ref([])
	const lsList = ref([])
	const keyword = ref('')
	const check1 = ref([])
	const checkList = ref([])
	const isEdit = ref(false)

	const totalPrice = computed(() => {
		let t = 0
		list.value.forEach(e => {
			const jg = e.cart_product.reduce((a, b) => {
				if (checkList.value.includes(b.id)) {
					a += b.price * b.cart_num
				}
				return a
			}, 0)
			t += jg
		})
		return t.toFixed(2)
	})

	const total = computed(() => {
		return list.value.reduce((a, b) => {
			return a + b.cart_product.length
		}, 0)
	})


	const getCartList = async () => {
		if (!token.value) return
		if (page.value === 1) list.value = []
		uni.showLoading({
			title: '加载中'
		})
		const {
			result
		} = await getMarketCartList({
			limit: 10,
			page: page.value
		})
		list.value = [...list.value, ...result.data]
		page.value++
		uni.hideLoading()
	}


	const checkAll = (res) => {
		if (!res) return checkList.value = []
		let check = []
		list.value.forEach(e => {
			const ids = e.cart_product.map(a => a.id)
			check = [...check, ...ids]
		})
		checkList.value = check
	}


	const delArrTips = () => {
		if (checkList.value.length === 0) return
		uni.showModal({
			content: '确定删除吗？',
			success: (res) => {
				if (res.confirm) delArr()
			}
		})
	}

	const delArr = async () => {
		uni.showLoading({
			title: '删除中'
		})
		await delMarketCart({
			cart_ids: checkList.value
		})
		page.value = 1
		check1.value = []
		checkList.value = [];
		await getCartList()
		uni.hideLoading()
		uni.$uv.toast('删除成功')
	}

	const handleSettlement = () => {
		if (checkList.value.length === 0) return
		/* 处理数据，保留商户结构，只过滤出选中的商品
		const selectedData = list.value.map(merchant => {
			// 过滤出该商户下选中的商品
			const selectedProducts = merchant.cart_product.filter(
				product => checkList.value.includes(product.id)
			);
			// 如果该商户没有选中的商品，则返回null（后续可以过滤掉）
			if (selectedProducts.length === 0) return null;
			// 返回新的商户对象，只包含选中的商品
			return {
				...merchant,
				cart_product: selectedProducts
			};
		}).filter(Boolean); // 过滤掉没有选中商品的商户
		console.log(selectedData)
		*/
		market.setOrderData(checkList.value);
		uni.navigateTo({
			url: '/pages-home/market/confirm_order'
		})
	}

	watch(keyword, () => {
		if (keyword.value) {
			uni.$uv.debounce(() => {
				if (lsList.value.length === 0) {
					lsList.value = JSON.parse(JSON.stringify(list.value))
				}
				const filteredList = lsList.value.map(item => {
					const cart_product = item.cart_product.filter(e => {
						return e.product_name.includes(keyword.value)
					})
					return {
						...item,
						cart_product
					}
				}).filter(item => item.cart_product.length > 0); // 额外过滤掉 cart_product 为空的商家
				list.value = filteredList
			})
		} else {
			if (lsList.value.length > 0) {
				list.value = lsList.value
				lsList.value = []
			}
		}
	})

	getCartList()
</script>

<style lang="scss" scoped>
	.market-cart {
		.hede {
			top: 0;
			z-index: 10;
			display: flex;
			height: 70upx;
			align-items: center;
			justify-content: space-between;
			position: sticky;
			padding: 0 30upx;
			padding-bottom: 20upx;
			background-color: #fff;
			padding-top: calc(var(--status-bar-height) + 50upx);
			// #ifdef MP-WEIXIN
			padding-top: calc(var(--status-bar-height) + 100upx); 
			// #endif  

			.t1 {
				margin-right: 50upx;

				text {
					&:first-child {
						color: #333;
						font-size: 40upx;
						font-weight: bold;
					}

					&:last-child {
						color: #333;
						font-size: 24upx;
					}
				}
			}

			.t2 {
				color: #333;
				font-size: 28upx;
				margin-left: 50upx;
			}
		}

		.jiesuan {
			left: 0;
			display: flex;
			align-items: center;
			justify-content: space-between;
			bottom: 100upx;
			// #ifdef MP-WEIXIN
			bottom: 150upx;  
			// #endif  
			width: 100%;
			box-sizing: border-box;
			position: fixed;
			padding: 20upx 30upx;
			background-color: #fff;
			.hj_lbl {
				font-size:28upx;
				color: #333;
				margin-right: 10upx;
			}
			.hj_price {
				color:#BC2721;
				font-size: 46upx;
				align-items: baseline;
				margin-right: 10upx;
			}
			.btn {
				width: 200upx;
				height: 80upx;
				background-color: #BC2721;
				color: #fff;
				font-size: 28upx;
				text-align: center;
				line-height: 80upx;
				border-radius: 40upx;
			}
		}
	}
</style>